package com.shaoshaohuo.app.wxapi;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.alipay.sdk.PayResult;
import com.alipay.sdk.SignUtils;
import com.alipay.sdk.app.PayTask;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.PayResultEneity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.pay.RechargeResultActivity;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;


//充值
public class RechangeActivity extends BaseActivity implements OnClickListener/*, IWXAPIEventHandler*/ {

	private TopbarView mTopbarView;
	
	private EditText mMoneyEdit;
	private View mWeixinLayout;
	private View mAlipayLayout;
	private CheckBox mWeixinCb;
	private CheckBox mAlipayCb;
	
	private Button mNextButton;
	
	protected PayResultEneity aliPayResult;
	protected PayResultEneity weixinResult;
	private String money;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rechange);
		initView();
		setUpView();
		initWx();
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mMoneyEdit = (EditText) this.findViewById(R.id.edittext_money);
		mWeixinLayout = this.findViewById(R.id.layout_weixin);
		mAlipayLayout = this.findViewById(R.id.layout_zhifubao);
		mWeixinCb = (CheckBox) this.findViewById(R.id.cb_weixin);
		mAlipayCb = (CheckBox) this.findViewById(R.id.cb_zhifubao);
		
		mNextButton = (Button) this.findViewById(R.id.button_next);
	}

	private void setUpView() {
		mTopbarView.setCenterText("充值");
		mTopbarView.setLeftView(true, true);

		mWeixinCb.setChecked(true);
		
		mWeixinLayout.setOnClickListener(this);
		mAlipayLayout.setOnClickListener(this);
		mNextButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_weixin:
			mWeixinCb.setChecked(true);
			mAlipayCb.setChecked(false);
			break;
		case R.id.layout_zhifubao:
			mWeixinCb.setChecked(false);
			mAlipayCb.setChecked(true);
			break;
		case R.id.button_next:
			money = mMoneyEdit.getText().toString().trim();
			if(TextUtils.isEmpty(money)){
				showToast("请输入充值金额");
				return;
			}
			if(mWeixinCb.isChecked()){
				payByWeixin();
			}else{
				payByAlipay();
			}
			break;
		}
	}
	
	private void payByAlipay() {
		startLoadingDialog();
		RequestService.getInstance().rechange(this, money,"alipay", PayResultEneity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					aliPayResult = (PayResultEneity) resultData;
//					showToast("支付成功");
					aliPay();
					
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}
	
	private void payByWeixin() {
		startLoadingDialog();
		RequestService.getInstance().rechange(this, money,"weixin", PayResultEneity.class, new RequestListener() {
			
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if(resultData.isOk()){
					weixinResult = (PayResultEneity) resultData;
                    WXPayEntryActivity.setCurrentPayWay(WXPayEntryActivity.PAY_RECHAEGE);
                    WXPayEntryActivity.setCurrentPayEntity(weixinResult);
					genPayReq();
					sendPayReq();
					finish();
				}else{
					showToast(resultData.getMsg());
				}
			}
			
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}
	

//    public static final String PARTNER = "2088911272543691";
//    public static final String SELLER = "zhifubao01@0071515.com";
//    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKRqS6q0N/W1hjln87ijcQtFJNjUpMn/mUtcedLt7hGK74rwpo33LH5WIB/1Zv1lUTHTixbb0D9z/XA7bOPc8A9aForWZ6bteR+OeFR7CGvCYSamOhQE1QBIBzG72c/viqLsQtWoUVttpKE+0w8w5oC1rKJhPJ9vgXHHXFoVNfZLAgMBAAECgYEAg7TOxoE1rrPqQQQ/3bG39bI+8R9uno4NK6x5vnlw00a7204p7eGKF+5AL7my9dv6rfJrIjWV3a653/UKpoIvHqRdpQflvUZwZZ5P+AgE533K8beFFMwk2dzPZ/W6M28t/QyFnRga/p87N51Y3oKwAmyhOM2ymyERmq1btygTbpkCQQDSS6ttU3Wie3VU5lxyJ4QyQxOk7ztf6A1Mw75ImdMTmiV7zfiM9rMyzfGv3drZ7KuwWATqYwFHan3a16qWTNDNAkEAyCX0cbEHEX3IvLmHS4mi1o2i4KWJ6SHCXxlk51HAUXctPI9TBEnzy+dphIKuRfwBor0aG3ntLGlOA29W60iDdwJAO+VFfCvrM04KixXZesH6iv5D2BQzSwuizhxqU+9MCSc8SdjOVAfn3i5+CeMcdDlOZTmMnN15/cc89Vm7wnc6eQJAF50CvfcY0mN4r2tkHvFaGN4U/VQKdUraV8XzNadbfUEGQULXlIX1EXV36X5ReUhGGSEeV2eHJ9o0rgsQwimH+QJAf0FQC9DuHUxkIl+1fTig3NXkkqKLpxjsvChSFy3A5E4HkyOAQT1zThAihY1prpwieK8YMAmQBNYzjR2ob9MWIA==".replace(" ", "");
//    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkakuqtDf1tYY5Z/O4o3ELRSTY1KTJ/5lLXHnS7e4Riu+K8KaN9yx+ViAf9Wb9ZVEx04sW29A/c/1wO2zj3PAPWhaK1mem7XkfjnhUewhrwmEmpjoUBNUASAcxu9nP74qi7ELVqFFbbaShPtMPMOaAtayiYTyfb4Fxx1xaFTX2SwIDAQAB".replace(" ", "");

//  public static final String PARTNER = "2088021439989711";
//  public static final String SELLER = "shaoshaowangluo@126.com";
//  public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMsV7plO2WV+aVRkB/1weYYRw2Fr5ZeF7xQSUBe4qEcdpkt02xZPO6MJ8tS3ll2yJebCj2zqskqXJIlIPw/AFLVTeK4K4pyM/qrt96RWZ4k9T+0B2f26/t5X1X0tFNhXVE0TKTQM35KGL4cZn2zy24w4gkQ7C71WmboyJdVdGcC5AgMBAAECgYB2gqHtzNmIJLCKkqUm/E+uMQd2/mPIfFv7toQOk69/cInuVo7TAgGnLtMJ1uhkXOVJOBhCUuMgK/siMYq7QjfSXcw/n8y+rITeh53x6gOwQVCFdUfruajMrEV4aIVkrY9GJwRPSUsUXK4kj8xrFtA9NfOVq9CvKER2Bhu3e0qGEQJBAPTc58Xvztkeeb5Px3+mHGD42j660uO7JlhfMdROo85lYcX8Bekcj66sIl2VNqgjECdScltg/cg/jIBCGTvX0rMCQQDUUpZytIi4e/OE4PbkRDVEpu0GBjuQoJ0pZ6TDb3+REsX86fw4M84RrfVIOsNuLQLd6BBs1o9M44xGe0zN5GTjAkEA0UV3RODmbQOx0ugGPd9vA6XLiK9NC9roM8DwKl4ne3+EJ5x0RL3nQsbU/BxJwTtuU90P5W8olptRblCPlminJwJAQOr3gR7d5rpPXMOD+Ys5VkJLmlnxgGj7ZJuB7xd6Q5sf2hKYwX5ldVZg9rKw6lDs3XiE/SIlMncofqxYcWNxzQJBAJFN5A2S9ozNp7m7gQVwDhMkIwPuzSUbsxEQ2Ql1T6D7JWX+Ym20hJBPfiNlbN+GjHUK41c5oW5ndKa5PzhqqaQ=".replace(" ", "");
//  public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB".replace(" ", "");

    
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    public void aliPay() {
        String orderInfo = getOrderInfo("田贸e通", "田贸e通 "+aliPayResult.getData().getMoney()+"元", money+"");
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RechangeActivity.this);
                // 调用支付接口
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * create the order info. 创建订单信息
     *
     */
    public String getOrderInfo(String subject, String body, String price) {
        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + Constants.PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + Constants.SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + aliPayResult.getData().getAlipay().getNotifyurl() +"\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;

    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content
     *            待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, Constants.RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     *
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    public String getOutTradeNo() {

        return aliPayResult.getData().getPayorderid();
    }

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     *
     */
    public void check(View v) {
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask payTask = new PayTask(RechangeActivity.this);
                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
                msg.obj = isExist;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SDK_PAY_FLAG: {
                PayResult resultObj = new PayResult((String) msg.obj);
                String resultStatus = resultObj.getResultStatus();

                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
//                    ToastUtil. toast("支付成功");
                	PayResult.ResultModel rm = PayResult.parseResult(resultObj.getResult());
					Intent successIntent = new Intent(RechangeActivity.this, RechargeResultActivity.class);
					successIntent.putExtra(RechargeResultActivity.FORWARD_KEY, RechargeResultActivity.FORWARD_USER_MAIN);
					successIntent.putExtra(RechargeResultActivity.KEY_RESULT, RechargeResultActivity.VALUE_SUCCESS);
					successIntent.putExtra(RechargeResultActivity.KEY_MONEY, aliPayResult.getData().getMoney() + "元");
					successIntent.putExtra(RechargeResultActivity.KEY_PAY_WAY, "支付宝");
					successIntent.putExtra(RechargeResultActivity.KEY_ORDER_ID, aliPayResult.getData().getOrderid());
					successIntent.putExtra(RechargeResultActivity.KEY_PAY_TIME, aliPayResult.getData().getPaytime());
					startActivity(successIntent);
                	finish();
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                	String result = null;
                    if (TextUtils.equals(resultStatus, "8000")) {
                        result = "支付结果确认中";
                    } else {
                        result = "支付失败";
                    }
					Intent successIntent = new Intent(RechangeActivity.this, RechargeResultActivity.class);
					successIntent.putExtra(RechargeResultActivity.FORWARD_KEY, RechargeResultActivity.FORWARD_USER_MAIN);
					successIntent.putExtra(RechargeResultActivity.KEY_RESULT, RechargeResultActivity.VALUE_FAILURE);
					successIntent.putExtra(RechargeResultActivity.KEY_FAILURE_REASON, result);
					startActivity(successIntent);
                	finish();
                }
                break;
            }
            case SDK_CHECK_FLAG: {
                ToastUtil. toast("检查结果为：" + msg.obj);
                break;
            }
            default:
                break;
            }
        };
    };
    
    
//    public static final String PARTNER = "2088911272543691";
//    public static final String SELLER = "zhifubao01@0071515.com";
//    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKRqS6q0N/W1hjln87ijcQtFJNjUpMn/mUtcedLt7hGK74rwpo33LH5WIB/1Zv1lUTHTixbb0D9z/XA7bOPc8A9aForWZ6bteR+OeFR7CGvCYSamOhQE1QBIBzG72c/viqLsQtWoUVttpKE+0w8w5oC1rKJhPJ9vgXHHXFoVNfZLAgMBAAECgYEAg7TOxoE1rrPqQQQ/3bG39bI+8R9uno4NK6x5vnlw00a7204p7eGKF+5AL7my9dv6rfJrIjWV3a653/UKpoIvHqRdpQflvUZwZZ5P+AgE533K8beFFMwk2dzPZ/W6M28t/QyFnRga/p87N51Y3oKwAmyhOM2ymyERmq1btygTbpkCQQDSS6ttU3Wie3VU5lxyJ4QyQxOk7ztf6A1Mw75ImdMTmiV7zfiM9rMyzfGv3drZ7KuwWATqYwFHan3a16qWTNDNAkEAyCX0cbEHEX3IvLmHS4mi1o2i4KWJ6SHCXxlk51HAUXctPI9TBEnzy+dphIKuRfwBor0aG3ntLGlOA29W60iDdwJAO+VFfCvrM04KixXZesH6iv5D2BQzSwuizhxqU+9MCSc8SdjOVAfn3i5+CeMcdDlOZTmMnN15/cc89Vm7wnc6eQJAF50CvfcY0mN4r2tkHvFaGN4U/VQKdUraV8XzNadbfUEGQULXlIX1EXV36X5ReUhGGSEeV2eHJ9o0rgsQwimH+QJAf0FQC9DuHUxkIl+1fTig3NXkkqKLpxjsvChSFy3A5E4HkyOAQT1zThAihY1prpwieK8YMAmQBNYzjR2ob9MWIA==".replace(" ", "");
//    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkakuqtDf1tYY5Z/O4o3ELRSTY1KTJ/5lLXHnS7e4Riu+K8KaN9yx+ViAf9Wb9ZVEx04sW29A/c/1wO2zj3PAPWhaK1mem7XkfjnhUewhrwmEmpjoUBNUASAcxu9nP74qi7ELVqFFbbaShPtMPMOaAtayiYTyfb4Fxx1xaFTX2SwIDAQAB".replace(" ", "");
//
//    private static final int SDK_PAY_FLAG = 1;
//    private static final int SDK_CHECK_FLAG = 2;
//
//    public void aliPay() {
//        
//        PayPopwindow payPopwindow = new PayPopwindow(this, "34546215445", 0.01);
//        payPopwindow.showLocation(mAlipayLayout);
//        
////        String orderInfo = getOrderInfo("神工呼叫", "神工呼叫"+1+"元", "0.1");
////        String sign = sign(orderInfo);
////        try {
////            // 仅需对sign 做URL编码
////            sign = URLEncoder.encode(sign, "UTF-8");
////        } catch (UnsupportedEncodingException e) {
////            e.printStackTrace();
////        }
////        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
////                + getSignType();
////
////        Runnable payRunnable = new Runnable() {
////
////            @Override
////            public void run() {
////                // 构造PayTask 对象
////                PayTask alipay = new PayTask(RechangeActivity.this);
////                // 调用支付接口
////                String result = alipay.pay(payInfo);
////
////                Message msg = new Message();
////                msg.what = SDK_PAY_FLAG;
////                msg.obj = result;
////                mHandler.sendMessage(msg);
////            }
////        };
////
////        Thread payThread = new Thread(payRunnable);
////        payThread.start();
//    }
//
//    /**
//     * create the order info. 创建订单信息
//     *
//     */
//    public String getOrderInfo(String subject, String body, String price) {
//        // 签约合作者身份ID
//        String orderInfo = "partner=" + "\"" + PARTNER + "\"";
//
//        // 签约卖家支付宝账号
//        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";
//
//        // 商户网站唯一订单号
//        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";
//
//        // 商品名称
//        orderInfo += "&subject=" + "\"" + subject + "\"";
//
//        // 商品详情
//        orderInfo += "&body=" + "\"" + body + "\"";
//
//        // 商品金额
//        orderInfo += "&total_fee=" + "\"" + price + "\"";
//
//        // 服务器异步通知页面路径
//        orderInfo += "&notify_url=" + "\"" + "http://api.shaohuo.feedss.com/alipay/notify"
//                + "\"";
//
//        // 服务接口名称， 固定值
//        orderInfo += "&service=\"mobile.securitypay.pay\"";
//
//        // 支付类型， 固定值
//        orderInfo += "&payment_type=\"1\"";
//
//        // 参数编码， 固定值
//        orderInfo += "&_input_charset=\"utf-8\"";
//
//        // 设置未付款交易的超时时间
//        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
//        // 取值范围：1m～15d。
//        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
//        // 该参数数值不接受小数点，如1.5h，可转换为90m。
//        orderInfo += "&it_b_pay=\"30m\"";
//
//        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
//        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
//
//        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//        orderInfo += "&return_url=\"m.alipay.com\"";
//
//        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
//        // orderInfo += "&paymethod=\"expressGateway\"";
//
//        return orderInfo;
//
//    }
//
//    /**
//     * sign the order info. 对订单信息进行签名
//     *
//     * @param content
//     *            待签名订单信息
//     */
//    public String sign(String content) {
//        return SignUtils.sign(content, RSA_PRIVATE);
//    }
//
//    /**
//     * get the sign type we use. 获取签名方式
//     *
//     */
//    public String getSignType() {
//        return "sign_type=\"RSA\"";
//    }
//
//    public String getOutTradeNo() {
//
//        return aliPayResult.getData().getPayorderid();
//    }
//
//    /**
//     * check whether the device has authentication alipay account.
//     * 查询终端设备是否存在支付宝认证账户
//     *
//     */
//    public void check(View v) {
//        Runnable checkRunnable = new Runnable() {
//
//            @Override
//            public void run() {
//                PayTask payTask = new PayTask(RechangeActivity.this);
//                boolean isExist = payTask.checkAccountIfExist();
//
//                Message msg = new Message();
//                msg.what = SDK_CHECK_FLAG;
//                msg.obj = isExist;
//                mHandler.sendMessage(msg);
//            }
//        };
//
//        Thread checkThread = new Thread(checkRunnable);
//        checkThread.start();
//    }
//
//    private Handler mHandler = new Handler() {
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//            case SDK_PAY_FLAG: {
//                PayResult resultObj = new PayResult((String) msg.obj);
//                String resultStatus = resultObj.getResultStatus();
//
//                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
//                if (TextUtils.equals(resultStatus, "9000")) {
//                    ToastUtil. toast("支付成功");
//                    //
//                } else {
//                    // 判断resultStatus 为非“9000”则代表可能支付失败
//                    // “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
//                    if (TextUtils.equals(resultStatus, "8000")) {
//                        ToastUtil. toast("支付结果确认中");
//                    } else {
//                        ToastUtil. toast("支付失败");
//                    }
//                }
//                break;
//            }
//            case SDK_CHECK_FLAG: {
//                ToastUtil. toast("检查结果为：" + msg.obj);
//                break;
//            }
//            default:
//                break;
//            }
//        };
//    };
    
    //---------------------wx
    
    PayReq req;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
//  TextView show;
//  Map<String,String> resultunifiedorder;
    StringBuffer sb;
    
    private void initWx(){
        req = new PayReq();
        sb=new StringBuffer();
        msgApi.registerApp(Constants.APP_ID);
    }

    
    private void genPayReq() {

        req.appId = Constants.APP_ID;
        req.partnerId = Constants.MCH_ID;
//        req.prepayId = resultunifiedorder.get("prepay_id");
        req.prepayId = weixinResult.getData().getWeixin().getPrepayid();
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n"+req.sign+"\n\n");

//        show.setText(sb.toString());

        Log.e("orion", signParams.toString());

    }
    private void sendPayReq() {
        msgApi.registerApp(Constants.APP_ID);
        msgApi.sendReq(req);
    }
    
//	@SuppressWarnings("deprecation")
//    private void genPayReq() {
//
//        req.appId = Constants.APP_ID;
//        req.partnerId = Constants.MCH_ID;
////      req.prepayId = resultunifiedorder.get("prepay_id");
////      req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id");
//        req.prepayId = weixinResult.getData().getWeixin().getPrepayid();
//        req.packageValue = "Sign=WXPay";
//        req.nonceStr = genNonceStr();
//        req.timeStamp = String.valueOf(genTimeStamp());
//
//
//        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
//        signParams.add(new BasicNameValuePair("appid", req.appId));
//        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
//        signParams.add(new BasicNameValuePair("package", req.packageValue));
//        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
//        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
//        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//
//        req.sign = genAppSign(signParams);
//
//        sb.append("sign\n"+req.sign+"\n\n");
//
////      show.setText(sb.toString());
//
//        Log.e("orion", signParams.toString());
//
//    }
    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }
    
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);

        this.sb.append("sign str\n"+sb.toString()+"\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion",appSign);
        return appSign;
    }
    
//    private void sendPayReq() {
//        msgApi.registerApp(Constants.APP_ID);
//        msgApi.sendReq(req);
//    }

//    @Override
//	protected void onNewIntent(Intent intent) {
//		super.onNewIntent(intent);
//		setIntent(intent);
//		msgApi.handleIntent(intent, this);
//	}

//	@Override
//	public void onReq(BaseReq req) {
//	}
//
//	@Override
//	public void onResp(BaseResp resp) {
//	    Logger.d(LogTag.UI, resp.toString());
//		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
//			if(resp.errCode == 0){
//				showToast("支付成功");
//				toOrderDetail();
//			}else if(resp.errCode == -1){
//				showToast("支付错误");
//			}else if(resp.errCode == -2){
//				showToast("支付取消");
//			}
//		}
//	}
	
}
